<?php
namespace app\admin\controller;

use app\common\model\AdminModel;
use app\common\model\RoleModel;

/**
 * 登录控制器
 * @author 贺强
 * @time   2021-06-21 11:51:27
 */
class Login extends Common
{
    /**
     * 登录页
     * @author 贺强
     * @time   2021-06-21 11:52:00
     */
    public function index()
    {
        if ($this->request->get('action') === 'logout') {
            session('admin', null);
        }
        return view();
    }

    /**
     * 登录
     * @author 贺强
     * @time   2021-06-21 13:52:54
     * @param  AdminModel $a AdminModel 实例
     */
    public function dologin(AdminModel $a)
    {
        $param = $this->request->post();
        if (empty($param['username']) || empty($param['pwd'])) {
            return ['status' => 3, 'info' => '用户名或密码不能为空'];
        }
        $time  = time();
        $un    = $param['username'];
        $admin = $a->getModel(['username' => $un], ['id', 'username', 'nickname', 'password', 'status', 'role_id', 'avatar', 'is_ip']);
        if (empty($admin)) {
            return ['status' => 2, 'info' => '用户名或密码错误'];
        }
        $flag = password_verify($param['pwd'], $admin['password']);
        if (!$flag) {
            return ['status' => 1, 'info' => '用户名或密码错误'];
        }
        if ($admin['status'] !== 1) {
            return ['status' => 4, 'info' => '账号审核不通过或被禁用，请联系管理员'];
        }
        $ip = get_client_ip();
        unset($admin['status']);
        $a->modify(['login_time' => $time, 'login_ip' => $ip], ['id' => $admin['id']]);
        // 赋值登录时间和登录IP
        $admin['login_time'] = $time;
        $admin['login_ip']   = $ip;
        // 赋值登录时间和登录IP结束
        $r     = new RoleModel();
        $menus = $r->getFieldValue('menus', ['id' => $admin['role_id']]);
        $menus = explode(',', $menus);
        // 赋值拥有权限的菜单
        $admin['roles'] = $menus;
        session('admin', $admin);
        return ['status' => 0, 'info' => '登录成功'];
    }
}
